
import { BasePage } from './../../basePage';
import { Component, Injector, Pipe } from '@angular/core';
import { IonicPage, NavController, NavParams, ActionSheetController } from 'ionic-angular';
import { PIC_URL } from "../../../providers/Config";
import { UserService } from '../../../providers/UserService';
import { StorageService } from '../../../providers/StorageService';
import { TabsPage } from '../../tabs/tabs';
import { StyleService } from '../../../providers/StyleService';
import { nailerService } from './../../../providers/nailerService';


declare var $: any
@IonicPage()
@Component({
  selector: 'page-add-img',
  templateUrl: 'add-img.html',
})
export class AddImgPage extends BasePage {
  imgarrP: any;
  serve1: any;
  lastImage: any;
  userinfo: any;
  fullPushh = []
  picture: string;
  returnImg = '';
  side: string = 'right';

  details: any;
  showSelect: boolean;
  fileObjList: any;
  circle1Class = 'circle1';//发布美图
  imgarr = []/**存储图片数组 */
  deleteVo = {
    file: ''
  }



  //缓存的id
  nail_type = [];
  /**上传参数 */
  nailNameObj = {
    artist_id: '',
    nail_name: '',
    nail_album: '',
    nail_types: '',
  }

  selectTools = []
  active: Array<boolean> = [];
  orderTool: string = '';
  activeM: Array<boolean> = [];
  selectMaterialss = [];
  orderMaterials: string = '';

  /**重写上传参数 */
  updataImgObj = {
    nail_price: null,
    nail_hold_time: null,
    nail_name: '',
    nail_desc: '',
    nail_album: [],
    nail_types: '',
    nail_consuming_time: null,
    nail_tools: [],
    nail_materials: [],
    applicable_scene: '',
    user_id: ''
  }



  T: any

  data = {};
  hands = [];
  types = [];
  hands2 = [];
  types2 = [];
  tools = [];
  tools2 = [];
  fullPush11 = [];
  fullPush22 = [];
  fullPush33 = [];
  /**发布服务所需参数 （定稿后更改） */
  issueServeiceVo = {
    type: null,
    shop_id: null,
    service_id: null,
    service_price: null,
    market_price: null,
    service_name: '',
    tools: '',
    material: '',
    imgs: '/Uploads/nail_album/2017-05-24/592515487bcfe_thumb_328-340.jpg',
    consuming_time: null,//分钟为单位
    applicable_scene: '',
    service_desc: '',
    keep_time: null
  }
  slide: boolean;

  // fileObjList=[];   //图片列表,与fileObjListChange形成双向数据绑定
  // imgpathlogo = '';     //显示门店logo
  // imgpathbg = '';     //显示门店背景

  // logoclass='logo';
  // imgpathbgclass='imgpathbg';
  constructor(
    injector: Injector,
    public styleProvider: StyleService,
    public userService: UserService,
    public stc: StorageService,
    public actionSheetCtrl: ActionSheetController,
    public nailerservice: nailerService
  ) {

    super(injector);
    this.picture = PIC_URL;
    this.userinfo = this.stc.read('userinfo');
    console.log(this.userinfo);
    this.updataImgObj.user_id = this.userinfo.user_id;
    this.nailNameObj.artist_id = this.userinfo['artist_id'];
    console.log(this.nailNameObj.artist_id)


    this.imgarr = this.navParams.get('detailObj');
    console.log(this.imgarr)

    console.log(this.imgarr)

  }

  async  ionViewDidLoad() {
    //     this.imgarr = this.navParams.get('detailObj');
    // console.log(this.imgarr)
    //     if (this.fullPushh.length == 0) {
    //       this.slide = true;
    //     } else {
    //       this.slide = false;
    //     }
    this.imgarr = this.issueServeiceVo.imgs.split(',');
    if (this.imgarr.length >= 3) {
      this.showSelect = true;
    } else {
      this.showSelect = false;
    }
    $('.btn').removeClass('active');
    $('.btn').eq(0).addClass('active');
    // this.getSearchConditionAPI()
    // this.uploadNailStyleFromArtistAPI();
    this.getSearchConditionAPI();
    console.log(this.stc.read('full2'))
    // this.T = setInterval(()=>{
    //   if(this.stc.read('full2') == null && this.stc.read("full")==null){
    //     this.nail_type='';
    //     this.fullPushh=["",""];
    //     this.fullPushh.shift();
    //   }else{
    //     this.fullPushh=[this.stc.read('full2'),this.stc.read('full2')];
    //     this.fullPushh.shift();
    //     this.nail_type=this.stc.read('full').toString();
    //   }
    //     console.log(this.fullPushh)
    //     console.log(this.nail_type);
    //   },1000)

    console.log('ionViewDidLoad AddImgPage');
    this.serve1 = this.navParams.get('serveImg')
    console.log(this.serve1)


    this.active = new Array(this.selectTools.length);
    this.activeM = new Array(this.selectMaterialss.length);
    // this.returnImg= this.nailNameObj.nail_album=this.navParams.get('returnImg');
    // console.log(this.returnImg);
    //let res = await this.userService.getAllToolsAPI();
    // if (res) {
    //   console.log(res);
    //   for (let tool of res['data']['tools']) {
    //     this.selectTools.push(tool['type_name'])
    //   }

    //   console.log(res['data']['material'])
    //   for (let Materials of res['data']['material']) {
    //     this.selectMaterialss.push(Materials['type_name'])
    //   }

    // }



  }


  /**上传美甲款式 */
  async uploadNailStyleFromArtistAPI() {
    this.updataImgObj.nail_album = this.imgarr;
    this.updataImgObj.nail_types = this.nail_type.toString();
    console.log(this.updataImgObj);
    let nickname = /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]{0,40}$/
    if (nickname.test(this.updataImgObj.nail_name)) {
      let res = await this.userService.uploadNailStyleFromArtistAPI(this.updataImgObj)
    } else {
      this.showAlert('您的昵称不合法哦')
    }




    // if(this.serve1==undefined || this.nail_type.length==0 ||this.nailNameObj.nail_name==""){
    //   this.showAlert("您有未填项，请填写完整后发布哦！")
    // }else{
    //     this.updataImgObj.nail_album=this.serve1;
    //     this.updataImgObj.nail_types=this.nail_type.toString();
    //     console.log(this.updataImgObj);
    //     let res=await this.userService.artistUploadNailStyleAPI(this.updataImgObj)
    //     console.log(res);
    //     if(res.code==1){
    //       let toast = this.toastCtrl.create({
    //         message: '发布成功，请等待审核通过！',
    //         duration: 2000,
    //         position: 'middle',
    //       });
    //       toast.present();
    //       setTimeout(() => {
    //         this.viewCtrl.dismiss();
    //       }, 2000);
    //     }else{
    //       let toast = this.toastCtrl.create({
    //         message: res.msg,
    //         duration:2000,
    //         position: 'middle',
    //       });
    //       toast.present();
    //       setTimeout(() => {
    //         this.viewCtrl.dismiss();
    //       }, 2000);
    //     }
    // }
  }

  /**分割图片字符串为图片数组 */
  splitimgstr(imgstr) {
    if (imgstr.indexOf(",") != -1) {
      this.imgarr = imgstr.split(",");
    } else {
      this.imgarr[0] = imgstr;
    }
  }



  //选择工具
  selectTool(i) {
    if (this.updataImgObj.nail_tools.length >= 4) {
      if (this.active[i]) {
        this.active[i] = false;
      } else {
        this.showAlert("最多只能选择4个标签哦！");
        this.active[i] = false;
      }


    } else if (this.updataImgObj.nail_tools.length < 4) {
      this.active[i] = !this.active[i];
    }


    if (this.active[i]) {
      this.updataImgObj.nail_tools.push(this.selectTools[i]);
    } else if (!this.active[i]) {
      this.updataImgObj.nail_tools = this.updataImgObj.nail_tools.filter((value) => { return value != this.selectTools[i] });
    }
    console.log(this.updataImgObj.nail_tools);
  }

  //选择工具完成
  okTool() {
    if (this.orderTool !== '') {
      this.updataImgObj.nail_tools.push(this.orderTool);
    }
    this.menuCtrl.close();

  }


  // 重置工具完成
  allbacTool() {
    for (let index = 0; index < this.active.length; index++) {
      this.active[index] = false;
      console.log(this.active[index])
    }
    this.updataImgObj.nail_tools = [];
    this.orderTool = '';

  }

  //选择材料
  selectMaterials(i) {
    if (this.updataImgObj.nail_materials.length >= 4) {
      if (this.activeM[i]) {
        this.activeM[i] = false;
      } else {
        this.showAlert("最多只能选择4个标签哦！");
        this.activeM[i] = false;
      }


    } else if (this.updataImgObj.nail_materials.length < 4) {
      this.activeM[i] = !this.activeM[i];
    }


    if (this.activeM[i]) {
      this.updataImgObj.nail_materials.push(this.selectMaterialss[i]);
    } else if (!this.activeM[i]) {
      this.updataImgObj.nail_materials = this.updataImgObj.nail_materials.filter((value) => { return value != this.selectMaterialss[i] });
    }
    console.log(this.updataImgObj.nail_materials);
  }

  // 材料选择完成
  okMaterials() {
    if (this.orderMaterials !== '') {
      this.updataImgObj.nail_materials.push(this.orderMaterials);
    }
    this.menuCtrl.close();
  }



  //重置材料
  allbacMaterials() {
    for (let index = 0; index < this.activeM.length; index++) {
      this.activeM[index] = false;
      console.log(this.activeM[index])
    }
    this.updataImgObj.nail_materials = [];
    this.orderMaterials = '';

  }


  /**关闭模态框 */
  dismissCLI() {
    this.navCtrl.pop();
  }
  ionViewDidLeave() {
    clearInterval(this.T)
  }

  //打开模菜单

  async select() {
    this.menuCtrl.enable(true, 'isDetail4');
    this.menuCtrl.enable(false, 'isDetail2');
    this.menuCtrl.enable(false, 'isDetail3');
    this.menuCtrl.enable(false, 'isDetail');

    this.menuCtrl.open();
    this.updataImgObj.nail_tools = this.updataImgObj.nail_tools.filter((value) => { return value != this.orderTool });


  }

  detail() {
    this.menuCtrl.enable(true, 'isDetail2');
    this.menuCtrl.enable(false, 'isDetail4');
    this.menuCtrl.enable(false, 'isDetail3');
    this.menuCtrl.enable(false, 'isDetail');

    this.menuCtrl.open();
  }

  selectM() {
    this.menuCtrl.enable(true, 'isDetail3');
    this.menuCtrl.enable(false, 'isDetail4');
    this.menuCtrl.enable(false, 'isDetail2');
    this.menuCtrl.enable(false, 'isDetail');

    this.menuCtrl.open();
    this.updataImgObj.nail_materials = this.updataImgObj.nail_materials.filter((value) => { return value != this.orderMaterials });
  }


  // //跳转到图片上传
  // uploadPic(){
  //   // this.navCtrl.push("CitySelectPage");
  //   let modal = this.modalCtrl.create("UploadPicPage");
  //   modal.onDidDismiss(data => {
  //     console.log(data);
  //     if(data){
  //       if (data.code == 1) {
  //         this.lastImage = data.data[0];
  //       }
  //     }else{

  //     }
  //   });
  //   modal.present();

  // }

  /** 
  * 美图描述里的风格选择
  */
  stylee(id) {
    console.log('点了外层div')
    if (this.fullPushh.length < 4) {
      for (let i = 0; i < this.types2.length; i++) {
        if (id == i) {
          for (let j = 0; j < this.fullPushh.length; j++) {
            if (this.types2[i] == this.fullPushh[j]) {
              this.remm1(id);
            }
          }
          // $('.btnsd').eq(id).addClass('active1');
          // $('.rem1d').eq(id).show();
          this.fullPushh.push(this.types2[i])
          console.log(this.fullPushh)
        }
      }

      /*将当前选中的类型的状态标 为 true*/
      this.types2[id].isCheck = true;


    } else {
      let toast = this.toastCtrl.create({
        message: "多可选四种款式",
        duration: 3000,
      }).present();
    }
  }
  stylee1(id) {
    if (this.fullPushh.length < 4) {
      for (let i = 0; i < this.hands2.length; i++) {
        if (id == i) {
          for (let j = 0; j < this.fullPushh.length; j++) {
            if (this.hands2[i] == this.fullPushh[j]) {
              this.remm2(id);
            }
          }
          // $('.btns1d').eq(id).addClass('active2')
          // $('.rem2d').eq(id).show();
          this.fullPushh.push(this.hands2[i])
          console.log(this.fullPushh)
        }
      }

      /*将当前选中的类型的状态标 为 true*/
      this.hands2[id].isCheck = true;

    } else {
      let toast = this.toastCtrl.create({
        message: "多可选四种款式",
        duration: 3000,
        // position:top,
      }).present();
    }
  }



  //描述里取消选择
  remm1(id) {
    console.log(id)

    /*取消 这个class*/
    this.types2[id].isCheck = false;

    console.log("点了里面的图片");
    $('.rem1d').eq(id).hide()
    $('.btnsd').eq(id).removeClass('.active1')
    for (let ids of this.fullPush11) {
      if (ids == id) {
        this.fullPush11 = [];
      }
    }
    for (var j = 0; j < this.types2.length; j++) {
      if (id == j) {
        console.log(this.types2[j]);
        this.fullPushh.indexOf(this.types2[j])
        console.log(this.fullPushh.indexOf(this.types2[j]))
        this.fullPushh.splice(this.fullPushh.indexOf(this.types2[j]), 1);
        console.log(this.fullPushh)
      }
    }
    event.stopPropagation();
  }
  remm2(id) {
    console.log(id)

    this.hands2[id].isCheck = false;

    $('.rem2d').eq(id).hide()
    $('.btns1d').eq(id).removeClass('active2')
    for (let ids of this.fullPush22) {
      if (ids == id) {
        this.fullPush22 = [];
      }
    }
    for (var i = 0; i < this.hands2.length; i++) {
      if (id == i) {
        console.log(this.hands2[i]);
        this.fullPushh.indexOf(this.hands2[i])
        console.log(this.fullPushh.indexOf(this.hands2[i]))
        this.fullPushh.splice(this.fullPushh.indexOf(this.hands2[i]), 1);
        console.log(this.fullPushh)
      }
    }
    event.stopPropagation();
  }
  //描述里重置
  /** 重置 */
  allbac() {
    this.types2.forEach((e, i) => {
      e.isCheck = false;
    })
    this.hands2.forEach((e, i) => {
      e.isCheck = false;
    })
    $('.btnsd').removeClass('active1');
    $('.btns1d').removeClass('active2');
    $('.rem1d').hide();
    $('.rem2d').hide();
    this.fullPush11 = [];
    this.fullPush22 = [];
    this.fullPush33 = [];
    this.fullPushh = [];
    console.log(this.fullPushh)
  }
  async ok() {
    if (this.fullPushh.length == 0) {
      this.slide = true;
    } else {
      this.slide = false;
    }
    this.stc.write('full', this.fullPushh);  //带id和款式名字
    if (this.fullPushh.length > 4) {
      this.showAlert("最多只能选择4个标签哦！");
      console.log(this.fullPushh)
    } else {
      console.log(this.fullPushh);
      this.menuCtrl.close();
    }
    this.fullPushh.forEach((e, i) => {
      this.nail_type.push(e.id);
      console.log(this.nail_type);
    })
  }

  /** 获取款式风格 */
  async getSearchConditionAPI() {
    console.log(this.data);
    let res = await this.styleProvider.getSearchConditionAPI(this.data);
    // console.log(res);
    console.log(res);
    this.hands = res.hands;
    this.hands2 = res.hands;
    this.types = res.type;
    this.types2 = res.type;
    // this.tools = res.tools;
    // this.tools2 = res.tools;
    console.log(this.hands);
    console.log(this.types);
    // console.log(this.tools);
  }


  presentActionSheetCamr() {
    let actionSheet = this.actionSheetCtrl.create({
      title: '选择',
      buttons: [
        {
          text: '拍照上传',
          handler: () => {

          }
        }, {
          text: '从相册上传',
          handler: () => {

          }
        },

        {
          text: '取消',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }

  async delImg(picFile, index) {

    this.deleteVo.file = picFile;
    let res = await this.nailerservice.delImg(this.deleteVo);

    if (res.code == 1) {
      this.toastCtrl.create({
        message: res.msg,
        duration: 3000,
        position: 'middle'
      }).present();
      this.imgarr.splice(index, 1);
    }

  }

  /**子页面返回处理数据 */
  returnapiimg(event) {
    this.fileObjList = event[0];
    console.log(this.fileObjList)
    this.imgarr.push(this.fileObjList);
    console.log(this.imgarr)
    if (this.imgarr.length >= 3) {
      this.showSelect = true;
    } else {
      this.showSelect = false;
    }
  }


  /**分割图片字符串为图片数组 */
  // splitimgstr(imgstr) {
  //   if (imgstr.indexOf(",") != -1) {
  //     this.imgarr = imgstr.split(",");
  //   } else {
  //     this.imgarr[0] = imgstr;
  //   }
  // }



}
